<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Meal_allocation extends CI_Controller {
	public function index(){
            $this->month();
	}
        
        public function month($year = null, $month = null){
            $data['title'] = "Meal Allocation";
            
            if ($year == null || $month == null){
                $year = date("Y");
                $month = date("m");
            }
            //Trying to workout how get the next 3 months

            $calendar = $this->createCalendar($year , $month);
                        
            $data['data'] = array (
                "calendar" => $calendar,
                "selected_month" => $year."/".$month,
                "baseurl" => base_url("meal_allocation/meal_allocation/showday/")
            );

            $data['css'] = array("meal_allocation.css", "datepicker/datepicker.min.css");
            $data['js'] = array("meal_allocation.js");

            $data['view'] = "meal_allocation/view_meal_allocation";
            $this->load->view('view_template',$data);
            
        }
        
        public function showday($year, $month, $day){
            $data['title'] = "Meal Allocation";
            //Don't allow if current day or before, or yesterday and before if an admin
            $find_date = date_to_mysql($year, $month, $day);
            $unix_date = strtotime($find_date);
            if ($unix_date <= time()){
                if (!(get_role_num() == admin_role() && date('Y-m-d', $unix_date) == date('Y-m-d'))){
                    $this->index();
                    return;
                }
            }
                        
            $this->load->model('categories');
            $categories = $this->categories->getAll();
            
            $this->load->model("defaults");
            
            $defaults = $this->defaults->get();
            
            $available_times = $this->defaults->getTimes();
            
            //Times for the select box
            $times = array();
            foreach($available_times->result() as $result){
                $times[$result->available_time_id] = $result->available_time_time;
            }
            
            
            $this->load->model('mealtimes');
            $current = $this->mealtimes->getMealsYMD($year, $month, $day);
            
            $mealtime = $this->mealtimes->getMealID($year,$month,$day);
            
            $mealtime_id = -1;
            
            $order_default = false;
            
            if ($mealtime != null){
                $mealtime_id = $mealtime->mealtime_id;
            }
            else{
                $mealtime_id = $this->mealtimes->create($year,$month,$day);
            }
            //Find if it is default orderable for today
                switch(intval(date('w', mktime(0,0,0,$month,$day,$year)))){
                    case 0://Sunday
                        $order_default = ($defaults->default_sunday == 1);
                        break;
                    case 1://Monday
                        $order_default = ($defaults->default_monday == 1);
                        break;
                    case 2://Tuesday
                        $order_default = ($defaults->default_tuesday == 1);
                        break;
                    case 3://Wednesday
                        $order_default = ($defaults->default_wednesday == 1);
                        break;
                    case 4://Thursday
                        $order_default = ($defaults->default_thursday == 1);
                        break;
                    case 5://Friday
                        $order_default = ($defaults->default_friday == 1);
                        break;
                    case 6://Saturday
                        $order_default = ($defaults->default_saturday == 1);
                        break;
                }
            
            if ($this->mealtimes->hasMeals($mealtime_id)){
                $defaults = (object) array(
                    "default_servetime" => $mealtime->mealtime_servetime,
                    "default_cutoff" => $mealtime->mealtime_cutoff,
                );
                $order_default = ($mealtime->mealtime_orderable == 1);//Returns true or false
            }
            
            $data['data'] = array (
                    "title"=>"Meal Allocation",
                    "date"=>date("l jS \of F Y", mktime(0, 0, 0, $month, $day, $year)),
                    "current" => $current,
                    "categories" => $categories,
                    "mealtime_id" => $mealtime_id,
                    "times" => $times,
                    "defaults" => $defaults,
                    "order_default" => $order_default
                );
                
                $data['css'] = array("meal_allocation_form.css");
                $data['js'] = array("meal_allocation_form.js");
                
                $data['view'] = "meal_allocation/view_meal_allocation_form";
                $this->load->view('view_template',$data);
        }
        
        public function searchResults(){
            $return = $this->ajax->post("search_term","category");
            extract($return);
            
            $this->load->model('meals');
            $meals = $this->meals->getWhere($search_term, $category);
            
            $options = array();
            
            foreach($meals->result() as $result){
                $options[$result->meal_id] = array(
                    'title'=> $result->meal_title,
                    'desc' => $result->meal_description
                );
            }
            
            $this->load->view("ajax/view_list", 
                array(
                    "options"=>$options,
                    "function"=>"selectMeal"
                )
            );
        }
        
        public function saveMeals(){
            extract($this->ajax->post("meals","mealtime","orderable","cutoff","servetime"));
            
            $this->load->model("mealtime_meals");
            $this->load->model("mealtimes");
            
            if ($this->mealtime_meals->updateMeals($meals, $mealtime) == null){
                echo "An error occurred updating the database.";
                return;
            }
                        
            if ($this->mealtimes->update($mealtime, $orderable, $cutoff, $servetime) == false){
                echo "An error occurred updating the database.";
                return;
            }
            echo "good";
        }
        
        private function createCalendar($year,$month){
            $base = base_url();
            
            $this->load->model('mealtimes');
            $mealtimes = $this->mealtimes->getMealtimes($year,$month);
            
            $data = array();
            
            foreach($mealtimes->result() as $result){
                
                $meals = $this->mealtimes->getMeals($result->mealtime_id);
                
                $date = $result->mealtime_date;
                $day = substr($date,strrpos($date,'-')+1); //Get the YYYY-MM-'DD' section (in the quotes) 
                $mealstring = "";
                foreach($meals->result() as $meal){
                    $mealstring .= $meal->meal_title."<br/>";
                }
                
                if ($mealstring != ""){
                    $data[intval($day)] = $mealstring;    
                }
            }
            $previous = "";
            if (date('n-Y') != date('n-Y',mktime(0,0,0,$month,1,$year))){
                //If not the current month
                $prevDate = mktime(0,0,0,$month-1,1,$year);
                $previous = "<a href='".base_url()."meal_allocation/meal_allocation/month/".date('Y/n',$prevDate)."'>".
                "<div id='date_prev'></div></a>";
            }
            
            $nextDate = mktime(0,0,0,$month+1,1,$year);
            $next = "<a href='".base_url()."meal_allocation/meal_allocation/month/".date('Y/n',$nextDate)."'>".
            "<div id='date_next'></div></a>";
            
            $config['day_type'] = 'long';
            //Make the calander template
            $config['template'] = "
                {table_open}
                        <table class='calendar'>
                {/table_open}
            
                {heading_title_cell}<th colspan='7' style='position: relative; vertical-align: top;'><div class='datepicker_center'>
            <input type='button' id='datePicker' value='{heading}'/><br/>
            <input id='datePickerText' type='text' value=''/>
            <div id='datePickerHelp'>Click to change</div>
            </div>
            $previous $next</th>{/heading_title_cell}
                {week_day_cell}
                        <th class='day_header'>{week_day}</th>
                {/week_day_cell}

                {cal_cell_content}	
                <div class='content'>
                        <a href='$base"."meal_allocation/meal_allocation/showDay/$year/$month/{day}'>
                    <span class='day'>{day}</span>
                    <div class='meals'>{content}</div></a>
                </div>
                {/cal_cell_content}

                {cal_cell_content_today}
                <div class='content today'>
                        <a href='$base"."meal_allocation/meal_allocation/showDay/$year/$month/{day}'>
                    <span class='day'>{day} - Today</span>
                    <div class='meals'>{content}</div></a>
                </div>
                {/cal_cell_content_today}

                {cal_cell_no_content}
                <div class='day_blank'>
                        <a href='$base"."meal_allocation/meal_allocation/showDay/$year/$month/{day}'>
                    <span class='day'>{day}</span>
                    <div class='meals'>(No Meals)</div></a>
                </div>
                {/cal_cell_no_content}

                {cal_cell_no_content_today}
                <div class='day_blank today'>
                        <a href='$base"."meal_allocation/meal_allocation/showDay/$year/$month/{day}'>
                    <span class='day'>{day} - Today</span>
                    <div class='meals'>(No Meals)</div></a>
                </div>
                {/cal_cell_no_content_today}

                {cal_cell_blank}
                        <div class='blank'></div>
                {/cal_cell_blank}
            ";
            $this->load->library("calendar", $config);
            
            return $this->calendar->generate($year, $month, $data);
        }
}